package com.cgsd.heyu.utils;

import android.content.Context;

import com.android.library.utils.ToastHelper;
import com.cgsd.heyu.ui.task.vo.WxPayVo;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;


/**
 * Author：sky on 2019/6/26 10:48.
 * Email：xcode126@126.com
 * Desc：微信支付工具
 */
public class WXPayUtil {

    private IWXAPI wxApi;
    private Map<String, String> map;

    public WXPayUtil(Context context, WxPayVo signParams, String payType) {
        if (!CommonTools.checkApkExist(context, "com.tencent.mm")) {
            ToastHelper.showDefaultToast("请先安装微信客户端");
            return;
        }
        map = getValue(signParams);
//        wxApi = WXAPIFactory.createWXAPI(context, null);
        wxApi = WXAPIFactory.createWXAPI(context, signParams.appid, false);
        wxApi.registerApp(signParams.appid);
        sendPayRequest(map,payType);
    }

    /**
     * 微信支付第二步
     * 使用第一步获取到的prepayid及支付api需要的其他参数一起发送支付请求
     * IWXAPI api;
     * PayReq request = new PayReq();
     * request.appId = "wxd930ea5d5a258f4f";
     * request.partnerId = "1900000109";
     * request.prepayId= "1101000000140415649af9fc314aa427",;
     * request.packageValue = "Sign=WXPay";
     * request.nonceStr= "1101000000140429eb40476f8896f4c9";
     * request.timeStamp= "1398746574";
     * request.sign= "7FFECB600D7157C5AA49810D2D8F28BC2811827B";
     * api.sendReq(req);
     */
    public void sendPayRequest(Map<String, String> orderInfo, String payType) {
        PayReq req = new PayReq();
        req.appId = orderInfo.get("appid");
        req.partnerId = orderInfo.get("partnerid");
        req.prepayId = orderInfo.get("prepayid");
        req.packageValue = orderInfo.get("package");
        req.nonceStr = orderInfo.get("noncestr");
        req.timeStamp = orderInfo.get("timestamp");
        req.sign = orderInfo.get("sign");
        req.extData = payType;
        wxApi.sendReq(req);
    }

    /**
     * 转换支付参数
     *
     * @param signParams
     * @return
     */
    public static Map<String, String> getValue(WxPayVo signParams) {
        Map<String, String> map = new HashMap<>();
        map.put("appid", signParams.appid);
        map.put("partnerid", signParams.partnerid);
        map.put("prepayid", signParams.prepayid);
        map.put("package", signParams.packageX);
        map.put("noncestr", signParams.noncestr);
        map.put("timestamp", signParams.timestamp);
        map.put("sign", signParams.sign);
        return map;
    }
}
